import {
    getBreadCrumbList,
    setTagNavListInLocalstorage,
    getMenuByRouter,
    getTagNavListFromLocalstorage,
    getHomeRoute,
    getNextRoute,
    routeHasExist,
    routeEqual,
    getRouteTitleHandled,
    localSave,
    localRead
} from "@/libs/util";
import beforeClose from "@/router/before-close";
import {
    saveErrorLogger,
    getAllMenus // 获取当前用户的全部菜单
} from "@/api/data";
import router from "@/router";
// import routers from "@/router/routers";
import config from "@/config";
import {
    routerDataHanding, // 遍历后台返回的路由数据，转为路由基础数据
    filterAsyncRouter, // 遍历路由基础数据，转换为前端组件对象
    menuListHanding, // 遍历菜单数据，将"原本不应挂载在根菜单"的数据，重新挂载到相应位置
    routerUpdateHandle // 遍历routes路由数据，1.手动往router.options.routes里添加数据；2.如routes里的name有变化，手动修改router.options.routes的name
} from "@/libs/router-util";
import { getValueByKey } from "@/libs/dataHanding"; // 根据对象数组某个key的value，查询另一个key的value
import { roleList } from "@/mock/role"; // mockData - 角色列表

const { homeName } = config;
const closePage = (state, route) => {
    const nextRoute = getNextRoute(state.tagNavList, route);
    state.tagNavList = state.tagNavList.filter(item => {
        return !routeEqual(item, route);
    });
    router.push(nextRoute);
};

export default {
    state: {
        breadCrumbList: [],
        tagNavList: [],
        homeRoute: {},
        local: localRead("local"),
        errorList: [],
        hasReadErrorPage: false,
        menuList: [] // 菜单数据
    },
    getters: {
        menuList: (state, getters, rootState) =>
            //   getMenuByRouter(routers, rootState.user.access),
            state.menuList, // 改造：动态菜单渲染
        errorCount: state => state.errorList.length
    },
    mutations: {
        setBreadCrumb(state, route) {
            state.breadCrumbList = getBreadCrumbList(route, state.homeRoute);
        },
        // 配置主页route
        setHomeRoute(state, routes) {
            state.homeRoute = getHomeRoute(routes, homeName);
        },
        setTagNavList(state, list) {
            let tagList = [];
            if (list) {
                tagList = [...list];
            } else tagList = getTagNavListFromLocalstorage() || [];
            if (tagList[0] && tagList[0].name !== homeName) tagList.shift();
            let homeTagIndex = tagList.findIndex(item => item.name === homeName);
            if (homeTagIndex > 0) {
                let homeTag = tagList.splice(homeTagIndex, 1)[0];
                tagList.unshift(homeTag);
            }
            state.tagNavList = tagList;
            setTagNavListInLocalstorage([...tagList]);
        },
        closeTag(state, route) {
            let tag = state.tagNavList.filter(item => routeEqual(item, route));
            route = tag[0] ? tag[0] : null;
            if (!route) return;
            if (
                route.meta &&
                route.meta.beforeCloseName &&
                route.meta.beforeCloseName in beforeClose
            ) {
                new Promise(beforeClose[route.meta.beforeCloseName]).then(close => {
                    if (close) {
                        closePage(state, route);
                    }
                });
            } else {
                closePage(state, route);
            }
        },
        addTag(state, { route, type = "unshift" }) {
            let router = getRouteTitleHandled(route);
            if (!routeHasExist(state.tagNavList, router)) {
                if (type === "push") state.tagNavList.push(router);
                else {
                    if (router.name === homeName) state.tagNavList.unshift(router);
                    else state.tagNavList.splice(1, 0, router);
                }
                setTagNavListInLocalstorage([...state.tagNavList]);
            }
        },
        setLocal(state, lang) {
            localSave("local", lang);
            state.local = lang;
        },
        addError(state, error) {
            state.errorList.push(error);
        },
        setHasReadErrorLoggerStatus(state, status = true) {
            state.hasReadErrorPage = status;
        },
        // 修改state.menuList，生成左侧菜单
        setMenuList(state, data) {
            state.menuList = getMenuByRouter(data.menuList, data.access);
        }
    },
    actions: {
        addErrorLog({ commit, rootState }, info) {
            if (!window.location.href.includes("error_logger_page")) {
                commit("setHasReadErrorLoggerStatus", false);
            }
            const {
                user: { token, userId, userName }
            } = rootState;
            let data = {
                ...info,
                time: Date.parse(new Date()),
                token,
                userId,
                userName
            };
            saveErrorLogger(info).then(() => {
                commit("addError", data);
            });
        },
        // 动态添加路由数据 -> 首次登录挂载路由
        addRouterData({ commit, rootState }, routes) {

            console.log("动态添加路由qian：", routes);

            /* 1.动态添加路由（不会立刻刷新，需要手动往router.options.routes里添加数据） */
            router.addRoutes(routes); // 动态添加路由
            routerUpdateHandle(routes, router); // 手动添加路由数据
            console.log("动态添加路由：", routes);
            /* 2.处理菜单数据 */
            var menuList = JSON.parse(JSON.stringify(routes));

            console.log("menuListHanding处理前：", menuList);
            menuList = menuListHanding(menuList); // 将"原本不应挂载在根菜单"的数据，重新挂载到相应位置
            console.log("左侧动态菜单：", menuList);
            /* 3.提交到 setMenuList，修改state.menuList */
            commit("setMenuList", {
                menuList: menuList,
                access: rootState.user.access
            });
        },
        // 获取动态路由数据
        getRouters({ dispatch, commit, rootState }, routes) {
            return new Promise((resolve, reject) => {
                var gotRouter = []; // 设置动态路由
                if (localRead("dynamicRouter-template") === "") {
                    /* localStorage里dynamicRouter值为空 -> 没有路由数据 -> 获取路由数据 */
                    console.log("获取路由：从api");
                    try {
                        console.log(rootState.user);
                        //rootState.user.token
                        getAllMenus()
                            .then(res => {
                                 console.log('getAllMenus:', res);
                                // /* 1.拿到路由接口数据 */
                             var routerData = res.data.data;


                                // var  jjson=[
                                //     {
                                //         id: "doc",
                                //         name: "doc",
                                //         title: "文档1111",
                                //         url: "https://simon9124.github.io/iview-dynamicRouter-doc/",
                                //         path: "outSidePath",
                                //         sort: 28,
                                //         parentId: "root",
                                //         ico: "ios-book",
                                //         isOutSide: true,
                                //         showLevel: "1",
                                //         description: "在线文档2222222"
                                //     },
                                //     {
                                //         id: "control",
                                //         name: "control",
                                //         title: "驾驶舱222222",
                                //         url: "control",
                                //         path: "screen",
                                //         sort: 26,
                                //         parentId: "root",
                                //         ico: "md-laptop",
                                //         isOutSide: false,
                                //         showLevel: "1",
                                //         description: "一级大屏"
                                //     },
                                //     {
                                //         id: "multilevel",
                                //         name: "multilevel",
                                //         title: "多级菜单",
                                //         url: "multilevel",
                                //         path: "Main",
                                //         sort: 24,
                                //         parentId: "root",
                                //         ico: "md-menu",
                                //         isOutSide: false,
                                //         showLevel: "2",
                                //         description: ""
                                //     },
                                //     {
                                //         id: "level_2_1",
                                //         name: "level_2_1",
                                //         title: "二级-1",
                                //         url: "level_2_1",
                                //         path: "template",
                                //         sort: 10,
                                //         parentId: "multilevel",
                                //         ico: "md-funnel",
                                //         isOutSide: false,
                                //         showLevel: "2",
                                //         description: ""
                                //     },
                                //     {
                                //         id: "level_2_2",
                                //         name: "level_2_2",
                                //         title: "二级-2",
                                //         url: "level_2_2",
                                //         path: "parentView",
                                //         sort: 8,
                                //         parentId: "multilevel",
                                //         ico: "md-funnel",
                                //         isOutSide: false,
                                //         showLevel: "2",
                                //         description: "内层模块"
                                //     },
                                //     {
                                //         id: "level_2_2_1",
                                //         name: "level_2_2_1",
                                //         title: "三级-1",
                                //         url: "level_2_2_1",
                                //         path: "template",
                                //         sort: 10,
                                //         parentId: "level_2_2",
                                //         ico: "md-funnel",
                                //         isOutSide: false,
                                //         showLevel: "2",
                                //         description: ""
                                //     },
                                //     {
                                //         id: "screen2",
                                //         name: "screen2",
                                //         title: "三级大屏",
                                //         url: "screen2",
                                //         path: "screen",
                                //         sort: 8,
                                //         parentId: "level_2_2",
                                //         ico: "md-laptop",
                                //         isOutSide: false,
                                //         showLevel: "1",
                                //         description: ""
                                //     },
                                //     {
                                //         id: "level_2_2_2",
                                //         name: "level_2_2_2",
                                //         title: "三级-2",
                                //         url: "level_2_2_2",
                                //         path: "template",
                                //         sort: 6,
                                //         parentId: "level_2_2",
                                //         ico: "md-funnel",
                                //         isOutSide: false,
                                //         showLevel: "2",
                                //         description: ""
                                //     },
                                //     {
                                //         id: "level_2_3",
                                //         name: "level_2_3",
                                //         title: "二级-3",
                                //         url: "level_2_3",
                                //         path: "template",
                                //         sort: 6,
                                //         parentId: "multilevel",
                                //         ico: "md-funnel",
                                //         isOutSide: false,
                                //         showLevel: "2",
                                //         description: ""
                                //     },
                                //     {
                                //         id: "screen",
                                //         name: "screen",
                                //         title: "二级大屏",
                                //         url: "screen",
                                //         path: "screen",
                                //         sort: 4,
                                //         parentId: "multilevel",
                                //         ico: "md-laptop",
                                //         isOutSide: false,
                                //         showLevel: "1",
                                //         description: ""
                                //     },
                                //     {
                                //         id: "github",
                                //         name: "github",
                                //         title: "github",
                                //         url: "https://github.com/simon9124/iview-dynamicRouter",
                                //         path: "outSidePath",
                                //         sort: 2,
                                //         parentId: "multilevel",
                                //         ico: "md-log-in",
                                //         isOutSide: true,
                                //         showLevel: "1",
                                //         description: "项目地址"
                                //     },
                                //     {
                                //         id: "singleMenu",
                                //         name: "single/menu",
                                //         title: "单极菜单",
                                //         url: "single/menu",
                                //         path: "template",
                                //         sort: 22,
                                //         parentId: "root",
                                //         ico: "md-document",
                                //         isOutSide: false,
                                //         showLevel: "2",
                                //         description: "单极父子结构"
                                //     },
                                //     {
                                //         id: "authority",
                                //         name: "authority",
                                //         title: "权限管理",
                                //         url: "authority",
                                //         path: "Main",
                                //         sort: 20,
                                //         parentId: "root",
                                //         ico: "md-settings",
                                //         isOutSide: false,
                                //         showLevel: "2",
                                //         description: "管理员专属"
                                //     },
                                //     {
                                //         id: "userManage",
                                //         name: "userManage",
                                //         title: "用户管理",
                                //         url: "userManage",
                                //         path: "authority/user",
                                //         sort: 10,
                                //         parentId: "authority",
                                //         ico: "ios-navigate",
                                //         isOutSide: false,
                                //         showLevel: "2",
                                //         description: ""
                                //     },
                                //     {
                                //         id: "roleManage",
                                //         name: "roleManage",
                                //         title: "角色管理",
                                //         url: "roleManage",
                                //         path: "authority/role",
                                //         sort: 8,
                                //         parentId: "authority",
                                //         ico: "ios-navigate",
                                //         isOutSide: false,
                                //         showLevel: "2",
                                //         description: ""
                                //     },
                                //     {
                                //         id: "menuManage",
                                //         name: "menuManage",
                                //         title: "菜单管理",
                                //         url: "menuManage",
                                //         path: "authority/menu",
                                //         sort: 6,
                                //         parentId: "authority",
                                //         ico: "ios-navigate",
                                //         isOutSide: false,
                                //         showLevel: "2",
                                //         description: ""
                                //     }
                                // ];
                                // routerData=jjson;
                                console.log("路由数据处理前：");
                                 console.log(routerData);

                                console.log("rootState:", rootState.user.access);
                                
                                /* 2.根据用户角色，处理该角色的路由数据（后端生成数据时忽略此步骤） */
                                // var menus = [];
                                // rootState.user.access.forEach(_access => {
                                //     // 把该用户所有的角色对应的菜单都加进来
                                //     menus = menus.concat(
                                //         getValueByKey(roleList, "name", _access, "menus")
                                //     );
                                // });
                                // menus = [...new Set(menus)]; // 然后去重
                                //  console.log('menus:',menus); // 获取该用户所有角色的所有菜单
                                // // /* 3.将路由动态数据与该角色拥有的菜单做比对筛选（后端生成数据时忽略此步骤） */
                                // routerData = routerData.filter(menu => {
                                //     return menus.some(_menu => _menu === menu.id); // 根据id全等筛选数据
                                // });

                                // console.log('routerData:',routerData); // 筛选出该角色拥有的路由数据
                                routerData = routerDataHanding(
                                    JSON.parse(JSON.stringify(routerData))
                                ); // 过滤路由，转为路由基础数据
                                console.log("路由数据处理后：", routerData);

                                
                                
                               // var routerData = testdata;

                                /* 4.处理后路由数据生成路由和菜单等 */
                                localSave("dynamicRouter-template", JSON.stringify(routerData)); // 存储到localStorage

                                //localSave("dynamicRouter-template1", JSON.stringify(jjson)); 
                                gotRouter = filterAsyncRouter(routerData); // 过滤路由，路由组件转换


                                console.log('gotRouter:', gotRouter);
                                dispatch("addRouterData", gotRouter).then(res => {

                                    resolve(gotRouter);

                                });
                            })
                            .catch(err => {
                                reject(err);
                            });
                    } catch (error) {
                        reject(error);
                    }
                } else {
                    /* 有路由数据 -> 直接从localStorage里面获取 */
                    console.log("获取路由：从localStorage");
                    /* 1.动态路由数据 */
                    gotRouter = filterAsyncRouter(
                        JSON.parse(localRead("dynamicRouter-template"))
                    ); // 过滤路由，路由组件转换
                    console.log("动态路由数据：", gotRouter);
                    /* 2.处理菜单数据 */
                    var menuList = JSON.parse(JSON.stringify(gotRouter));
                    menuList = menuListHanding(menuList); // 将"原本不应挂载在根菜单"的数据，重新挂载到相应位置
                    console.log("左侧动态菜单：", menuList);
                    /* 3.提交到 setMenuList，修改state.menuList */
                    commit("setMenuList", {
                        menuList: menuList,
                        access: rootState.user.access
                    });
                    resolve();
                }
            });
        }
    }
};
